package org.fearsomej.list.server;

import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.fearsomej.list.domain.DataUser;
import org.fearsomej.list.domain.FearsomeCalendarEntry;
import org.fearsomej.list.domain.MappedDomainClass;
import org.fearsomej.list.domain.Task;
import org.fearsomej.list.server.data.EMF;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GWTServiceImpl extends RemoteServiceServlet {

	

	protected void persistEntity(MappedDomainClass entity) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(entity);
		} finally {
			em.close();
		}
	}

	protected DataUser getDataUser() {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		EntityManager em = EMF.get().createEntityManager();
		DataUser dataUser = null;
		try {
			Query query = em
					.createQuery("select du from DataUser du where du.userId = :userId");
			query.setParameter("userId", user.getUserId());
			List<DataUser> users = query.getResultList();
			if (users != null && users.size() > 0) {
				dataUser = users.get(0);
			}
			if (dataUser == null) {
				dataUser = new DataUser();
				dataUser.setUserId(user.getUserId());
				dataUser.setNickname(user.getNickname());
				em.persist(dataUser);
			}
		} finally {
			em.close();
		}
		return dataUser;
	}

	public FearsomeCalendarEntry createCalendarEntry(Task task, DataUser user)
			throws IOException, GeneralSecurityException, ServiceException {
		if (user == null) {
			user = getDataUser();
		}
		FearsomeCalendarEntry returnEntry = null;
		if (user.getCalendarSessionToken() == null) {
			String onetimeUseToken = null;
			if (getThreadLocalRequest().getParameter("token") != null) {
				onetimeUseToken = AuthSubUtil
						.getTokenFromReply(getThreadLocalRequest()
								.getQueryString());
			}
			if (onetimeUseToken == null) {
				String requestUrl = AuthSubUtil.getRequestUrl(
						getThreadLocalRequest().getRequestURI(),
						"http://www.google.com/calendar/feeds/", false, true);
				getThreadLocalResponse().sendRedirect(requestUrl);
				return returnEntry;
			} else {
				String sessionToken = AuthSubUtil.exchangeForSessionToken(
						onetimeUseToken, null);
				user.setCalendarSessionToken(sessionToken);
				persistEntity(user);
			}
			CalendarService calendarService = new CalendarService(
					"Fearsome List");
			calendarService.setAuthSubToken(user.getCalendarSessionToken(),
					null);
			CalendarEventEntry newEntry = new CalendarEventEntry();
			newEntry.setContent(new PlainTextConstruct(task.getTitle()));
			newEntry.setQuickAdd(true);
			newEntry = calendarService
					.insert(
							new URL(
									"http://www.google.com/calendar/feeds/kevin@fearsomej.org/private/full"),
							newEntry);
			returnEntry = new FearsomeCalendarEntry();
		}
		return returnEntry;
	}

}
